package com.corner.ui.activity;

import android.os.Bundle;
import android.os.Handler;

import com.corner.R;
import com.corner.model.cornerservice.domain.User;
import com.corner.presenter.imp.SplashPresenter;
import com.corner.ui.base.BaseActivity;
import com.corner.utils.AppManager;
import com.corner.utils.DateFormatUtil;

/**
 * ============================================================
 * <p/>
 * 版权 ：Walker
 * <p/>
 * 作者：韩炜伟
 * <p/>
 * 版本 ：1.0
 * <p/>
 * 创建日期 ： 2015年4月8日上午10:39:18
 * <p/>
 * 描述 ： 欢迎界面
 * <p/>
 * 修订历史 ：
 * <p/>
 * ============================================================
 **/
public class SplashActivity extends BaseActivity<SplashPresenter> {
    protected static final int GOHOME = 0;

    protected static final int GOLOGIN = 1;

    private long currentTimeInMills;

    // 跳转handler
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GOHOME:
                    goHome();
                    break;
                case GOLOGIN:
                    goLogin();
                    break;
            }
        }
    };

    @Override
    protected SplashPresenter createP() {
        return new SplashPresenter();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_splash);
    }

    @Override
    protected void initData() {
        // 记录时间
        currentTimeInMills = DateFormatUtil.getCurrentTimeInMills();

        // 1.获取当前用户
        User currentUser = User.getCurrentUser();

        if (currentUser == null) {
            // 2.不存在，跳登录注册页面
            waitGo(GOLOGIN);
        } else {
            // 3.用户存在，跳主页
            waitGo(GOHOME);
        }
    }

    @Override
    protected void onNetStatusChanged(boolean isConnected) {
        super.onNetStatusChanged(isConnected);
        if (isConnected) {
            presenter.checkUpdate();
        }
    }

    /**
     * 等待至少1.5s
     */
    private void waitGo(int tag) {
        long timeOff = DateFormatUtil.getCurrentTimeInMills()
                - currentTimeInMills;
        if (timeOff < 2500) {
            handler.sendEmptyMessageDelayed(tag, 2500 - timeOff);
        } else {
            handler.sendEmptyMessage(tag);
        }
    }

    /**
     * 去登录注册
     */
    private void goLogin() {
        jump(LoginAndRegisterActivity.class);
        overridePendingTransition(R.anim.splash_alpha_in, R.anim.splash_alpha_out);
        AppManager.getInstance().finishActivity(this);
    }

    /**
     * 去主页面
     */
    private void goHome() {
        jump(MainActivity.class);
        overridePendingTransition(R.anim.splash_alpha_in, R.anim.splash_alpha_out);
        AppManager.getInstance().finishActivity(this);
    }

    @Override
    protected void setOnClick() {
    }

}
